package com.vhall.component.service.export.manager;

import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.constant.HttpConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.connection.stream.StringRecord;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * 导出组件mq类操作
 *
 * @author yuanzh
 * @date 2021/11/22
 */
@Slf4j
@Component
public class ExportMqManager {

    @Value("${vhall.export.admin-stream-name:export-admin-stream}")
    private String exportStreamName;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * admin导出任务创建成功后，发送异步消息进行任务处理
     *
     * @param exportId 导出id
     * @return 消息发送成功与否
     */
    public boolean sendAdminExportCreateMessage(Integer exportId) {
        // 发送消息
        try {
            StringRecord stringRecord = StreamRecords.string(Collections.singletonMap(HttpConstant.DATA, String.valueOf(exportId)))
                    .withStreamKey(exportStreamName);
            RecordId recordId = stringRedisTemplate.opsForStream().add(stringRecord);
            log.info("export表插入数据的消息发送成功,[{}]", recordId);
            return true;
        } catch (Exception e) {
            log.info("export表插入数据的消息发送失败,[{}]", e.getMessage());
            // TODO 错误码需完善
            throw new BusinessException("export表插入数据的消息发送失败");
        }
    }
}
